//
//  ScanViewController.m
//  AriseSamePro
//
//  Created by 包日守 on 15/10/27.
//  Copyright © 2015年 Arise. All rights reserved.
//



#import "ScanViewController.h"
#import "AFNetworking.h"
#import "ARGlobalInterface.h"
#import "ARChannelInfoModel.h"
#import "ChannelTableViewController.h"

#import "ZJQRCoder.h"

#import "ARChannelTableViewFactory.h"


@interface ScanViewController ()<AVCaptureMetadataOutputObjectsDelegate,UIImagePickerControllerDelegate,UINavigationControllerDelegate>

@property (nonatomic) BOOL isFind;
@property (nonatomic) NSString *channleURL;

@end

@implementation ScanViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    self.title = @"扫描二维码添加频道";
    self.isFind = NO;
    
    [self readQRcode];
    
}

- (void) viewDidAppear:(BOOL)animated
{

    [self.session startRunning];

}

- (void) viewDidDisappear:(BOOL)animated
{
    [self.session stopRunning];

}

- (IBAction)takePhotoInLibriy:(id)sender {
    
    @try {
        if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeSavedPhotosAlbum]) {
            UIImagePickerController *imgPickerVC = [[UIImagePickerController alloc] init];
            [imgPickerVC setSourceType:UIImagePickerControllerSourceTypePhotoLibrary];
            [imgPickerVC.navigationBar setBarStyle:UIBarStyleDefault];
            [imgPickerVC setDelegate:self];
            [imgPickerVC setAllowsEditing:NO];
            //显示Image Picker
            [self presentViewController:imgPickerVC animated:YES completion:nil];
        }else {
            NSLog(@"Album is not available.");
        }
    }
    @catch (NSException *exception) {
        //Error
        NSLog(@"Album is not available.");
    }


}


- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker{
    NSLog(@"Image Picker Controller canceled.");
    //Cancel以后将ImagePicker删除
    [self dismissViewControllerAnimated:NO completion:nil];
}
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
    NSLog(@"Image Picker Controller did finish picking media.");
    
    
    //TODO:选择照片或者照相完成以后的处理
    

    UIImage *image = info[UIImagePickerControllerOriginalImage];

    [self loadDataInserver:[[ZJQRCoder sharedInstance] decodeWithImage:image]];
  
    
    [self dismissViewControllerAnimated:NO completion:nil];
}



- (void) readQRcode
{
    AVCaptureDevice *device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
    
    
    NSError *error = nil;
    AVCaptureDeviceInput *input = [AVCaptureDeviceInput  deviceInputWithDevice:device error:&error];
    
    if (error) {
        NSLog(@"没有摄像头-%@", error.localizedDescription);
        return;
    }
    
    AVCaptureMetadataOutput *output = [[AVCaptureMetadataOutput alloc] init];
    
    
    [output setMetadataObjectsDelegate:self queue:dispatch_get_main_queue()];
    
    
    AVCaptureSession *session = [[AVCaptureSession alloc] init];
    
    [session addInput:input];
    [session addOutput:output];
    
    [output setMetadataObjectTypes:@[AVMetadataObjectTypeQRCode]];
    
    
    AVCaptureVideoPreviewLayer *preview = [AVCaptureVideoPreviewLayer layerWithSession:session];
    
    
    
    
    [preview setVideoGravity:AVLayerVideoGravityResizeAspectFill];
    
    [preview setFrame:self.view.bounds];
    
    [self.view.layer insertSublayer:preview atIndex:0];
    
    //[self.view.layer addSublayer:preview];
    self.previewLayer = preview;
    
    CGSize size = [UIScreen mainScreen].bounds.size;
    
    UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, size.width, size.height - 64 - 49)];
    imageView.image = [UIImage imageNamed:@"scan_qrcode_bg@2x"];
    imageView.alpha = 0.9;
    [self.view addSubview:imageView];
    
    [session startRunning];
    
    self.session = session;
    

}

#pragma mark - 输出代理方法
// 此方法是在识别到QRCode，并且完成转换
// 如果QRCode的内容越大，转换需要的时间就越长
- (void)captureOutput:(AVCaptureOutput *)captureOutput didOutputMetadataObjects:(NSArray *)metadataObjects fromConnection:(AVCaptureConnection *)connection
{
    
    
    
    // 会频繁的扫描，调用代理方法
    // 1. 如果扫描完成，停止会话
    //[self.session stopRunning];
    // 2. 删除预览图层
    //[self.previewLayer removeFromSuperlayer];
    if (self.isFind) {
        return;
    }
    
    self.isFind = YES;
    
    NSLog(@"%@", metadataObjects);
    // 3. 设置界面显示扫描结果
    
    if (metadataObjects.count > 0) {
        AVMetadataMachineReadableCodeObject *obj = metadataObjects[0];
        // 提示：如果需要对url或者名片等信息进行扫描，可以在此进行扩展！
        //_captureLabel.text = obj.stringValue;
        NSLog(@"obj.stringValue = %@",obj.stringValue);
        [self loadDataInserver:obj.stringValue];
        
        
        
        /*
        UIAlertView *alertView = [[UIAlertView alloc] init];
        alertView.message = [NSString stringWithFormat:@"二维码数据: %@",obj.stringValue];
        [alertView addButtonWithTitle:@"取消"];
        [alertView show];
        */
    }

}



- (void) loadDataInserver:(NSString *) strurl
{

    
    AudioServicesPlaySystemSound(kSystemSoundID_Vibrate);
    
    NSString *url = strurl;
    NSString *index = [url componentsSeparatedByString:@"/"][4];
    
    
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    
    [manager GET:[ARGlobalInterface channelDetailServerURLWithID:index] parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
        
        
        NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
        
        ARChannelInfoModel *modelInfo = [[ARChannelInfoModel alloc] init];
        
        [modelInfo setValuesForKeysWithDictionary:dict[@"data"]];
        
        if (!modelInfo.name) {
            UIAlertController *ac = [UIAlertController alertControllerWithTitle:nil message:@"没有发现任何频道"  preferredStyle:UIAlertControllerStyleAlert];
            
            [ac addAction:[UIAlertAction actionWithTitle:@"知道了" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
                
                self.isFind = NO;
            }]];
                        
            [self presentViewController:ac animated:YES completion:nil];
            
        }else
        {
            UIAlertController *ac = [UIAlertController alertControllerWithTitle:modelInfo.name message:[NSString stringWithFormat:@"发现频道：%@，是否下载打开频道？",modelInfo.name]  preferredStyle:UIAlertControllerStyleAlert];
            
            [ac addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
                
                self.isFind = NO;
            }]];
            [ac addAction:[UIAlertAction actionWithTitle:@"进入频道" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
                
                
                ChannelTableViewController *channelVC = [ARChannelTableViewFactory channelTableViewWithCate:modelInfo.cate WithTitle:modelInfo.name WithIndex:modelInfo.index];
                
                if (channelVC) {
                    [self.navigationController pushViewController:channelVC animated:YES];
                }
                
            
                /*
                if ( [modelInfo.cate isEqualToString:@"8"]|| [modelInfo.cate isEqualToString:@"3"]) {
                    ChannelTableViewController *channelVC = [[ChannelTableViewController alloc] init];
                    
                    
                    channelVC.index = modelInfo.index;
                    channelVC.cate = modelInfo.cate;
                    channelVC.title = modelInfo.name;
                    
                    [self.navigationController pushViewController:channelVC animated:YES];
                 
                }
                */
                
                
                
                
            }]];
            
            [self presentViewController:ac animated:YES completion:nil];
                 
        
        }
        
   
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        
    }];

}




- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
